'use client';

import { useState } from 'react';
import { 
  BookOpen, 
  Plus, 
  Search, 
  Calendar, 
  CheckCircle2, 
  Clock, 
  AlertCircle,
  FileText,
  Edit,
  Trash2
} from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { FadeIn } from '@/components/ui/motion';

// 模拟数据
const mockHomeworks = [
  {
    id: 1,
    title: '语文作文练习',
    subject: '语文',
    description: '以"我的家乡"为题，写一篇不少于800字的作文。要求：内容具体，感情真挚，语言流畅。',
    assignDate: '2023-10-15',
    dueDate: '2023-10-20',
    status: 'active'
  },
  {
    id: 2,
    title: '数学应用题练习',
    subject: '数学',
    description: '完成教材第56页习题1-10，要求写出完整的解题过程。',
    assignDate: '2023-10-12',
    dueDate: '2023-10-18',
    status: 'active'
  },
  {
    id: 3,
    title: '英语单词默写',
    subject: '英语',
    description: '背诵并默写Unit 3的全部单词和短语，要求拼写正确。',
    assignDate: '2023-10-10',
    dueDate: '2023-10-15',
    status: 'completed'
  },
  {
    id: 4,
    title: '科学实验报告',
    subject: '科学',
    description: '根据课堂上进行的"植物生长"实验，撰写一份实验报告，包括实验目的、材料、步骤、观察结果和结论。',
    assignDate: '2023-10-08',
    dueDate: '2023-10-14',
    status: 'completed'
  }
];

const subjects = ['语文', '数学', '英语', '科学', '历史', '地理', '音乐', '美术', '体育'];

export default function HomeworkPage() {
  const [activeTab, setActiveTab] = useState('all');
  const [searchTerm, setSearchTerm] = useState('');
  const [dialogOpen, setDialogOpen] = useState(false);
  const [homeworks, setHomeworks] = useState(mockHomeworks);
  
  // 新作业表单状态
  const [newHomework, setNewHomework] = useState({
    title: '',
    subject: '',
    description: '',
    dueDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0] // 默认一周后截止
  });
  
  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setNewHomework(prev => ({ ...prev, [name]: value }));
  };
  
  // 处理科目选择变化
  const handleSubjectChange = (value: string) => {
    setNewHomework(prev => ({ ...prev, subject: value }));
  };
  
  // 发布新作业
  const handlePublishHomework = () => {
    const today = new Date().toISOString().split('T')[0];
    const newHomeworkItem = {
      id: homeworks.length + 1,
      ...newHomework,
      assignDate: today,
      status: 'active'
    };
    
    setHomeworks([newHomeworkItem, ...homeworks]);
    setDialogOpen(false);
    setNewHomework({
      title: '',
      subject: '',
      description: '',
      dueDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
    });
    
    // 实际项目中应该调用API保存数据
    console.log('发布新作业', newHomeworkItem);
  };
  
  // 删除作业
  const handleDeleteHomework = (id: number) => {
    if (window.confirm('确定要删除这个作业吗？')) {
      setHomeworks(homeworks.filter(hw => hw.id !== id));
      // 实际项目中应该调用API删除数据
      console.log('删除作业', id);
    }
  };
  
  // 过滤作业列表
  const filteredHomeworks = homeworks.filter(homework => {
    const matchesSearch = homework.title.toLowerCase().includes(searchTerm.toLowerCase()) || 
                         homework.subject.toLowerCase().includes(searchTerm.toLowerCase());
    
    if (activeTab === 'all') return matchesSearch;
    if (activeTab === 'active') return homework.status === 'active' && matchesSearch;
    if (activeTab === 'completed') return homework.status === 'completed' && matchesSearch;
    
    return matchesSearch;
  });
  
  // 计算统计数据
  const totalHomeworks = homeworks.length;
  const activeHomeworks = homeworks.filter(hw => hw.status === 'active').length;
  const completedHomeworks = homeworks.filter(hw => hw.status === 'completed').length;

  return (
    <FadeIn>
      <div className="container mx-auto py-6">
        <div className="flex justify-between items-center mb-6">
          <h1 className="text-2xl font-bold">作业管理</h1>
          <div className="flex space-x-2">
            <div className="relative">
              <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-500" />
              <Input
                type="search"
                placeholder="搜索作业..."
                className="pl-8 w-[200px] md:w-[250px]"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
              <DialogTrigger asChild>
                <Button className="flex items-center">
                  <Plus className="mr-2 h-4 w-4" />
                  发布作业
                </Button>
              </DialogTrigger>
              <DialogContent className="sm:max-w-[600px]">
                <DialogHeader>
                  <DialogTitle>发布新作业</DialogTitle>
                  <DialogDescription>
                    填写作业信息，发布给班级学生
                  </DialogDescription>
                </DialogHeader>
                <div className="grid gap-4 py-4">
                  <div className="grid gap-2">
                    <Label htmlFor="title">作业标题</Label>
                    <Input 
                      id="title" 
                      name="title"
                      placeholder="请输入作业标题" 
                      value={newHomework.title}
                      onChange={handleInputChange}
                    />
                  </div>
                  <div className="grid gap-2">
                    <Label htmlFor="subject">科目</Label>
                    <Select value={newHomework.subject} onValueChange={handleSubjectChange}>
                      <SelectTrigger>
                        <SelectValue placeholder="选择科目" />
                      </SelectTrigger>
                      <SelectContent>
                        {subjects.map(subject => (
                          <SelectItem key={subject} value={subject}>{subject}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="grid gap-2">
                    <Label htmlFor="description">作业内容</Label>
                    <Textarea 
                      id="description" 
                      name="description"
                      placeholder="请描述作业内容和要求..." 
                      className="min-h-[120px]"
                      value={newHomework.description}
                      onChange={handleInputChange}
                    />
                  </div>
                  <div className="grid gap-2">
                    <Label htmlFor="dueDate">截止日期</Label>
                    <Input 
                      id="dueDate" 
                      name="dueDate"
                      type="date" 
                      value={newHomework.dueDate}
                      onChange={handleInputChange}
                    />
                  </div>
                </div>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setDialogOpen(false)}>取消</Button>
                  <Button onClick={handlePublishHomework}>发布作业</Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>
        </div>
        
        {/* 作业统计卡片 */}
        <div className="mb-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center">
                <BookOpen className="h-5 w-5 mr-2" />
                作业统计概览
              </CardTitle>
              <CardDescription>
                班级作业情况统计
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="bg-blue-50 p-4 rounded-lg">
                  <div className="flex justify-between items-center">
                    <div>
                      <p className="text-sm text-gray-500">总作业数</p>
                      <p className="text-2xl font-bold text-blue-600">{totalHomeworks}</p>
                    </div>
                    <div className="p-2 bg-blue-100 rounded-full">
                      <FileText className="h-6 w-6 text-blue-600" />
                    </div>
                  </div>
                </div>
                
                <div className="bg-green-50 p-4 rounded-lg">
                  <div className="flex justify-between items-center">
                    <div>
                      <p className="text-sm text-gray-500">已完成</p>
                      <p className="text-2xl font-bold text-green-600">{completedHomeworks}</p>
                    </div>
                    <div className="p-2 bg-green-100 rounded-full">
                      <CheckCircle2 className="h-6 w-6 text-green-600" />
                    </div>
                  </div>
                </div>
                
                <div className="bg-yellow-50 p-4 rounded-lg">
                  <div className="flex justify-between items-center">
                    <div>
                      <p className="text-sm text-gray-500">进行中</p>
                      <p className="text-2xl font-bold text-yellow-600">{activeHomeworks}</p>
                    </div>
                    <div className="p-2 bg-yellow-100 rounded-full">
                      <Clock className="h-6 w-6 text-yellow-600" />
                    </div>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
        
        {/* 选项卡 */}
        <Tabs value={activeTab} onValueChange={setActiveTab} className="mb-6">
          <TabsList className="mb-4">
            <TabsTrigger value="all">全部作业</TabsTrigger>
            <TabsTrigger value="active">进行中</TabsTrigger>
            <TabsTrigger value="completed">已完成</TabsTrigger>
          </TabsList>
          
          <TabsContent value={activeTab}>
            <div className="space-y-4">
              {filteredHomeworks.length > 0 ? (
                filteredHomeworks.map((homework) => (
                  <Card key={homework.id}>
                    <CardHeader className="pb-2">
                      <div className="flex justify-between items-start">
                        <div>
                          <div className="flex items-center space-x-2">
                            <CardTitle className="text-lg">{homework.title}</CardTitle>
                            <Badge className={`${
                              homework.status === 'active' ? 'bg-yellow-100 text-yellow-800' : 'bg-green-100 text-green-800'
                            }`}>
                              {homework.status === 'active' ? '进行中' : '已完成'}
                            </Badge>
                          </div>
                          <CardDescription>
                            {homework.subject} · 发布日期: {homework.assignDate} · 截止日期: {homework.dueDate}
                          </CardDescription>
                        </div>
                        <div className="flex space-x-2">
                          <Button variant="outline" size="sm" className="h-8">
                            <Edit className="h-4 w-4 mr-1" />
                            <span>编辑</span>
                          </Button>
                          <Button 
                            variant="outline" 
                            size="sm" 
                            className="h-8 text-red-600 hover:text-red-700"
                            onClick={() => handleDeleteHomework(homework.id)}
                          >
                            <Trash2 className="h-4 w-4 mr-1" />
                            <span>删除</span>
                          </Button>
                        </div>
                      </div>
                    </CardHeader>
                    <CardContent>
                      <p className="text-gray-700 mb-4">{homework.description}</p>
                      <div className="flex items-center">
                        <Calendar className="h-4 w-4 text-gray-500 mr-1" />
                        <span className="text-sm text-gray-500">
                          {homework.status === 'active' 
                            ? `还有 ${Math.max(0, Math.floor((new Date(homework.dueDate).getTime() - Date.now()) / (24 * 60 * 60 * 1000)))} 天截止` 
                            : '已截止'}
                        </span>
                      </div>
                    </CardContent>
                  </Card>
                ))
              ) : (
                <div className="text-center py-8">
                  <p className="text-gray-500">暂无作业</p>
                </div>
              )}
            </div>
          </TabsContent>
        </Tabs>
      </div>
    </FadeIn>
  );
}
